<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Qwen3-0.6B API 测试工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, #1a237e, #3949ab);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .tabs {
            display: flex;
            border-bottom: 2px solid #e0e0e0;
            margin-bottom: 20px;
        }

        .tab-button {
            padding: 15px 30px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1.1em;
            font-weight: 600;
            color: #666;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
        }

        .tab-button.active {
            color: #1a237e;
            border-bottom: 3px solid #1a237e;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
            font-size: 1em;
        }

        textarea {
            width: 100%;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1em;
            resize: vertical;
            min-height: 120px;
            font-family: inherit;
            transition: border-color 0.3s ease;
        }

        textarea:focus {
            outline: none;
            border-color: #1a237e;
            box-shadow: 0 0 0 3px rgba(26, 35, 126, 0.1);
        }

        .params-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        input[type="number"],
        input[type="range"] {
            width: 100%;
            padding: 10px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1em;
            transition: border-color 0.3s ease;
        }

        input[type="number"]:focus,
        input[type="range"]:focus {
            outline: none;
            border-color: #1a237e;
            box-shadow: 0 0 0 3px rgba(26, 35, 126, 0.1);
        }

        .range-container {
            position: relative;
        }

        .range-value {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: #1a237e;
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.9em;
            min-width: 40px;
            text-align: center;
        }

        .buttons {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
        }

        button {
            padding: 12px 30px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .primary-button {
            background: linear-gradient(90deg, #1a237e, #3949ab);
            color: white;
        }

        .primary-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(26, 35, 126, 0.3);
        }

        .secondary-button {
            background: #e0e0e0;
            color: #333;
        }

        .secondary-button:hover {
            background: #d0d0d0;
        }

        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .response-section {
            background: #f8f9fa;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
        }

        .response-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e0e0e0;
        }

        .response-title {
            font-weight: 600;
            color: #555;
            font-size: 1.1em;
        }

        .copy-button {
            padding: 6px 12px;
            background: #e0e0e0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9em;
            transition: background 0.3s ease;
        }

        .copy-button:hover {
            background: #d0d0d0;
        }

        .response-content {
            font-family: 'Courier New', Courier, monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
            max-height: 500px;
            overflow-y: auto;
            padding: 10px;
            background: white;
            border-radius: 4px;
            border: 1px solid #e0e0e0;
        }

        .status-section {
            margin-top: 20px;
            padding: 15px;
            background: #e3f2fd;
            border-radius: 8px;
            border-left: 4px solid #2196f3;
        }

        .status-success {
            background: #e8f5e9;
            border-left-color: #4caf50;
        }

        .status-error {
            background: #ffebee;
            border-left-color: #f44336;
        }

        .status-loading {
            background: #fff8e1;
            border-left-color: #ff9800;
        }

        .api-info {
            background: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .api-info h3 {
            color: #1a237e;
            margin-bottom: 10px;
        }

        .api-endpoint {
            background: #e0e0e0;
            padding: 10px;
            border-radius: 4px;
            font-family: 'Courier New', Courier, monospace;
            margin-bottom: 10px;
        }

        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #1a237e;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .highlight {
            background: #fff3cd;
            padding: 2px 4px;
            border-radius: 3px;
            font-weight: 600;
        }

        @media (max-width: 768px) {
            .container {
                margin: 0;
                border-radius: 0;
                box-shadow: none;
            }

            .header h1 {
                font-size: 2em;
            }

            .tabs {
                flex-direction: column;
            }

            .tab-button {
                text-align: left;
                border-bottom: 1px solid #e0e0e0;
            }

            .buttons {
                flex-direction: column;
            }

            .params-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>Qwen3-0.6B API 测试工具</h1>
            <p>通过此界面测试 Qwen3-0.6B 模型的 API 功能</p>
        </div>

        <div class="content">
            <div class="tabs">
                <button class="tab-button active" onclick="switchTab('generate-tab', this)">文本生成</button>
                <button class="tab-button" onclick="switchTab('health-tab', this)">健康检查</button>
                <button class="tab-button" onclick="switchTab('about-tab', this)">关于 API</button>
            </div>

            <!-- 文本生成标签页 -->
            <div id="generate-tab" class="tab-content active">
                <div class="form-group">
                    <label for="prompt">输入提示词：</label>
                    <textarea id="prompt" placeholder="请输入您的问题或提示..."></textarea>
                </div>

                <div class="params-grid">
                    <div class="form-group">
                        <label for="max_new_tokens">最大新标记数：</label>
                        <input type="number" id="max_new_tokens" min="1" max="2048" value="1024">
                    </div>

                    <div class="form-group">
                        <label for="temperature">温度 (Temperature)：</label>
                        <div class="range-container">
                            <input type="range" id="temperature" min="0" max="2" step="0.1" value="0.6">
                            <span class="range-value" id="temperature-value">0.6</span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="top_p">Top-p：</label>
                        <div class="range-container">
                            <input type="range" id="top_p" min="0" max="1" step="0.05" value="0.95">
                            <span class="range-value" id="top_p-value">0.95</span>
                        </div>
                    </div>
                </div>

                <div class="buttons">
                    <button class="primary-button" id="generate-button" onclick="generateText()">
                        <span>生成文本</span>
                        <div class="loading-spinner" id="generate-spinner" style="display: none;"></div>
                    </button>
                    <button class="secondary-button" onclick="clearResults()">清除结果</button>
                </div>

                <div class="response-section">
                    <div class="response-header">
                        <div class="response-title">响应结果：</div>
                        <button class="copy-button" onclick="copyResponse()">复制</button>
                    </div>
                    <div class="response-content" id="generate-response"></div>
                </div>

                <div class="status-section" id="generate-status">
                    <p>准备就绪。请输入提示词并点击生成按钮。</p>
                </div>
            </div>

            <!-- 健康检查标签页 -->
            <div id="health-tab" class="tab-content">
                <div class="api-info">
                    <h3>健康检查 API</h3>
                    <div class="api-endpoint">GET http://127.0.0.1:5000/api/health</div>
                    <p>此接口用于检查 Qwen3-0.6B 模型服务的运行状态。</p>
                </div>

                <div class="buttons">
                    <button class="primary-button" id="health-button" onclick="checkHealth()">
                        <span>检查健康状态</span>
                        <div class="loading-spinner" id="health-spinner" style="display: none;"></div>
                    </button>
                </div>

                <div class="response-section">
                    <div class="response-header">
                        <div class="response-title">响应结果：</div>
                        <button class="copy-button" onclick="copyHealthResponse()">复制</button>
                    </div>
                    <div class="response-content" id="health-response"></div>
                </div>

                <div class="status-section" id="health-status">
                    <p>点击按钮检查模型服务的健康状态。</p>
                </div>
            </div>

            <!-- 关于 API 标签页 -->
            <div id="about-tab" class="tab-content">
                <div class="api-info">
                    <h3>API 接口说明</h3>

                    <h4>1. 文本生成 API</h4>
                    <div class="api-endpoint">POST http://127.0.0.1:5000/api/generate</div>
                    <p><strong>请求体 (JSON)：</strong></p>
                    <pre>
{
  "prompt": "您的问题或提示"
}
                    </pre>
                    <p><strong>响应格式：</strong></p>
                    <pre>
{
  "original_response": "原始响应内容",
  "thinking": "模型思考内容（如果有）",
  "answer": "模型回答内容（如果有）"
}
                    </pre>

                    <h4>2. 健康检查 API</h4>
                    <div class="api-endpoint">GET http://127.0.0.1:5000/api/health</div>
                    <p><strong>响应格式：</strong></p>
                    <pre>
{
  "status": "healthy",
  "model": "Qwen/Qwen3-0.6B"
}
                    </pre>

                    <h4>3. 参数说明</h4>
                    <ul>
                        <li><strong>max_new_tokens：</strong>生成的最大标记数量，控制回复长度</li>
                        <li><strong>temperature：</strong>采样温度，越高生成内容越随机（0-2）</li>
                        <li><strong>top_p：</strong>核采样参数，控制生成内容的多样性（0-1）</li>
                    </ul>

                    <h4>4. 注意事项</h4>
                    <ul>
                        <li>请确保 Qwen3-0.6B 模型服务正在端口 5000 上运行</li>
                        <li>如果出现 CORS 错误，请在服务器端配置允许的跨域请求</li>
                        <li>在 CPU 环境下，生成文本可能需要较长时间</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 标签切换功能
        function switchTab(tabId, element) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });

            // 移除所有标签按钮的激活状态
            document.querySelectorAll('.tab-button').forEach(button => {
                button.classList.remove('active');
            });

            // 显示选中的标签内容
            document.getElementById(tabId).classList.add('active');

            // 激活选中的标签按钮
            if (element) {
                element.classList.add('active');
            }
        }

        // 实时显示滑块值
        document.getElementById('temperature').addEventListener('input', function () {
            document.getElementById('temperature-value').textContent = this.value;
        });

        document.getElementById('top_p').addEventListener('input', function () {
            document.getElementById('top_p-value').textContent = this.value;
        });

        // 健康检查功能
        function checkHealth() {
            const healthButton = document.getElementById('health-button');
            const healthSpinner = document.getElementById('health-spinner');
            const healthResponse = document.getElementById('health-response');
            const healthStatus = document.getElementById('health-status');

            // 禁用按钮并显示加载状态
            healthButton.disabled = true;
            healthSpinner.style.display = 'block';
            healthStatus.className = 'status-section status-loading';
            healthStatus.innerHTML = '<p>正在检查服务健康状态...</p>';
            healthResponse.textContent = '';

            fetch('http://localhost:5000/api/health')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // 显示成功结果
                    healthResponse.textContent = JSON.stringify(data, null, 2);
                    healthStatus.className = 'status-section status-success';
                    healthStatus.innerHTML = `<p>✅ 服务运行正常！模型：<span class="highlight">${data.model}</span></p>`;
                })
                .catch(error => {
                    // 显示错误信息
                    healthResponse.textContent = error.toString();
                    healthStatus.className = 'status-section status-error';
                    healthStatus.innerHTML = `<p>❌ 服务检查失败：${error.message}</p>`;
                    console.error('Health check error:', error);
                })
                .finally(() => {
                    // 恢复按钮状态
                    healthButton.disabled = false;
                    healthSpinner.style.display = 'none';
                });
        }

        // 文本生成功能
        function generateText() {
            const prompt = document.getElementById('prompt').value.trim();
            const generateButton = document.getElementById('generate-button');
            const generateSpinner = document.getElementById('generate-spinner');
            const generateResponse = document.getElementById('generate-response');
            const generateStatus = document.getElementById('generate-status');

            // 验证输入
            if (!prompt) {
                generateStatus.className = 'status-section status-error';
                generateStatus.innerHTML = '<p>❌ 请输入提示词！</p>';
                return;
            }

            // 获取参数
            const maxNewTokens = parseInt(document.getElementById('max_new_tokens').value);
            const temperature = parseFloat(document.getElementById('temperature').value);
            const topP = parseFloat(document.getElementById('top_p').value);

            // 禁用按钮并显示加载状态
            generateButton.disabled = true;
            generateSpinner.style.display = 'block';
            generateStatus.className = 'status-section status-loading';
            generateStatus.innerHTML = '<p>正在生成文本，请稍候...</p>';
            generateResponse.textContent = '';

            // 构建请求体
            const requestBody = {
                prompt: prompt
            };

            fetch('http://localhost:5000/api/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    // 格式化显示响应
                    const formattedResponse = JSON.stringify(data, null, 2);
                    generateResponse.textContent = formattedResponse;

                    // 显示成功状态
                    generateStatus.className = 'status-section status-success';
                    generateStatus.innerHTML = `<p>✅ 文本生成成功！</p>`;

                    // 如果有思考和回答内容，显示更友好的结果
                    if (data.thinking && data.answer) {
                        const formattedDisplay = `思考内容:\n${data.thinking}\n\n回答内容:\n${data.answer}`;
                        generateResponse.textContent = formattedDisplay + '\n\n--- 原始 JSON 响应 ---\n' + formattedResponse;
                    }
                })
                .catch(error => {
                    // 显示错误信息
                    generateResponse.textContent = error.toString();
                    generateStatus.className = 'status-section status-error';
                    generateStatus.innerHTML = `<p>❌ 文本生成失败：${error.message}</p>`;
                    console.error('Text generation error:', error);
                })
                .finally(() => {
                    // 恢复按钮状态
                    generateButton.disabled = false;
                    generateSpinner.style.display = 'none';
                });
        }

        // 复制响应结果
        function copyResponse() {
            const responseText = document.getElementById('generate-response').textContent;
            if (responseText) {
                navigator.clipboard.writeText(responseText).then(() => {
                    const generateStatus = document.getElementById('generate-status');
                    generateStatus.className = 'status-section status-success';
                    generateStatus.innerHTML = '<p>✅ 响应结果已复制到剪贴板！</p>';

                    // 3秒后恢复状态
                    setTimeout(() => {
                        generateStatus.innerHTML = '<p>文本生成完成。</p>';
                    }, 3000);
                }).catch(err => {
                    console.error('复制失败:', err);
                });
            }
        }

        function copyHealthResponse() {
            const responseText = document.getElementById('health-response').textContent;
            if (responseText) {
                navigator.clipboard.writeText(responseText).then(() => {
                    const healthStatus = document.getElementById('health-status');
                    healthStatus.className = 'status-section status-success';
                    healthStatus.innerHTML = '<p>✅ 响应结果已复制到剪贴板！</p>';

                    // 3秒后恢复状态
                    setTimeout(() => {
                        healthStatus.innerHTML = '<p>服务状态检查完成。</p>';
                    }, 3000);
                }).catch(err => {
                    console.error('复制失败:', err);
                });
            }
        }

        // 清除结果
        function clearResults() {
            document.getElementById('generate-response').textContent = '';
            document.getElementById('generate-status').className = 'status-section';
            document.getElementById('generate-status').innerHTML = '<p>准备就绪。请输入提示词并点击生成按钮。</p>';
        }

        // 页面加载完成后初始化
        window.onload = function () {
            // 设置滑块初始值显示
            document.getElementById('temperature-value').textContent = '0.6';
            document.getElementById('top_p-value').textContent = '0.95';

            // 添加键盘快捷键支持
            document.addEventListener('keydown', function (e) {
                // Ctrl+Enter 触发文本生成
                if (e.ctrlKey && e.key === 'Enter') {
                    // 只有在文本生成标签页激活时才触发
                    if (document.getElementById('generate-tab').classList.contains('active')) {
                        generateText();
                    }
                }
            });

            // 添加错误处理和提示
            window.addEventListener('error', function(event) {
                console.error('页面错误:', event.message, '在文件:', event.filename, '行号:', event.lineno);
            });
        };
    </script>
</body>

</html>